package demo.hdz.mediacodecdecode.customview;

import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import demo.hdz.mediacodecdecode.filter.BaseFilter;

/**
 * @author hdz
 * @date 2022/05/28 17:04
 */
public class GLRenderer implements GLSurfaceView.Renderer {

    private final float[] transformMatrix = new float[16];

    private final SurfaceTexture mSurfaceTexture;
    private final int mOESTextureId;
    private BaseFilter mFilter;

    public GLRenderer(SurfaceTexture texture, int textureId, BaseFilter filter) {
        this.mSurfaceTexture = texture;
        this.mOESTextureId = textureId;
        this.mFilter = filter;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        this.mFilter.init();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        // 设置绘图的窗口大小
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        if (mSurfaceTexture == null) {
            return;
        }

        //更新纹理图像
        mSurfaceTexture.updateTexImage();
        //获取外部纹理的矩阵，用来确定纹理的采样位置，没有此矩阵可能导致图像翻转等问题
        mSurfaceTexture.getTransformMatrix(transformMatrix);

        //clear
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

        mFilter.drawFrame(mOESTextureId, transformMatrix);
    }
}
